package com.sphd.Restaurant.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.sphd.Restaurant.R;
import com.sphd.Restaurant.base.BaseActivity;
import com.sphd.Restaurant.infos.LoginInfo;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.LoginP;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.utils.MyUtils;
import com.sphd.Restaurant.views.ClearEditText;
import com.sphd.Restaurant.views.LoginV;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class LoginActivity extends BaseActivity implements LoginV, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.login_name)
    ClearEditText loginName;
    @BindView(R.id.login_pwd)
    ClearEditText loginPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };
    @BindView(R.id.isShowPassword)
    ToggleButton isShowPassword;
    @BindView(R.id.tv_forgetpw)
    TextView tvForgetpw;
    @BindView(R.id.cb_rememberpw)
    CheckBox cbRememberpw;
    boolean isRemeber = true;
    @BindView(R.id.btn_register)
    TextView btnRegister;
    @BindView(R.id.content_login)
    LinearLayout contentLogin;
    Intent intent;
    LoginP loginP;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> AppManager.getAppManager().finishActivity(this));

        isShowPassword.setOnCheckedChangeListener(this);
        cbRememberpw.setOnCheckedChangeListener(this);
    }

    private void initView() {
        setToolBar(toolbar, "登录", true);
        intent = getIntent();
        loginP = new LoginP(this);
        if (intent.hasExtra(Constants.TAG))
            if (intent.getStringExtra(Constants.TAG).equals(RegisterActivity.class.getName())) {
                loginName.setText(intent.getStringExtra(Constants.USERPHONE));
                loginPwd.setText(intent.getStringExtra(Constants.PWD));
                if (MyUtils.isNetworkAvailable(context)) {
                    cheNull();
                }
            }

    }

    @OnClick({R.id.btn_register, R.id.btn_login})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_forgetpw:
                //忘记密码
                bundle.putInt(Constants.TYPE, 1);
                startActivity(RegisterActivity.class, bundle);
                break;

            case R.id.btn_register:
                //注册
                bundle.putInt(Constants.TYPE, 0);
                startActivity(RegisterActivity.class, bundle);
                break;
            case R.id.btn_login:
                if (MyUtils.isNetworkAvailable(context)) {
                    cheNull();
                }
                break;
        }
    }

    private void cheNull() {
        if (isNoEmpty(loginName.getText().toString()) && isNoEmpty(loginPwd.getText().toString())) {
            if (MyUtils.isMobileNO(loginName.getText().toString())) {
                LoginActivityPermissionsDispatcher.onSuccedWithCheck(this);
            } else {
                toast("请输入正确的手机号码");
            }
        } else {
            toast("账号或密码不能为空");
        }
    }

    private void login() {
        TelephonyManager telephonemanage = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imeinum = telephonemanage.getDeviceId();
        putString(Constants.DEVID, imeinum);
        MyUtils myUtils = new MyUtils();
        String url = Model.HTTPURL + Model.LOGIN + "username=" + loginName.getText().toString() + "&password="
                + myUtils.getkeyBeanofStr(loginPwd.getText().toString()) + "&userID="
                + getString(Constants.BAIDUUSERID) + "&channelID=" + getString(Constants.BAIDUCHANGEID)
                + "&deviceID=" + imeinum + "&systemType=android";

        loginP.addData(url);
}


    @Override
    public void showdialog() {
        showDialog();
    }

    @Override
    public void dissmissdialog() {
        dissMissDialog();
    }

    @Override
    public void LoginOk(LoginInfo loginInfo) {
        toast("登陆成功");
        putString(Constants.USERPHONE, loginInfo.getUser_phone());
        putString(Constants.USERPHOTO, loginInfo.getUser_photo());
        putInt(Constants.SEX, loginInfo.getUser_sex());
        putString(Constants.USERNAME, loginInfo.getUser_name());
        putInt(Constants.USER_ID, loginInfo.getId());
        putBoolean(Constants.ISLOGIN, true);
        if (isRemeber) {
            putString(Constants.PWD, loginPwd.getText().toString().trim());
        }else {
            removeKey(Constants.PWD);
        }
        if (intent.hasExtra(Constants.TAG)) {
            if (intent.getStringExtra(Constants.TAG).equals(RestaurantPageActivity.class.getName())) {
                AppManager.getAppManager().finishActivity(this);
            }
        } else {
            Bundle bundle = crratBundle();
            AppManager.getAppManager().delAllActivityExceptMain(LoginActivity.class);
            bundle.putInt(Constants.JUMPPAGE, 0);
            bundle.putSerializable(Constants.LOGININFO, loginInfo);
            startActivity(MainActivity.class, bundle);
            AppManager.getAppManager().finishActivity(this);
        }
    }

    @Override
    public void LoginError() {
        toast("账号或密码错误，请重试。");
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.cb_rememberpw:
                isRemeber = isChecked;
                Log.e("isChecked========", isChecked + "");
                break;
            case R.id.isShowPassword:
                if (isChecked) {
                    //隐藏
                    loginPwd.setInputType(0x90);
                } else {
                    //明文显示
                    loginPwd.setInputType(0x81);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Activity&从堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }


    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    void onSucced() {
        login();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.READ_PHONE_STATE)
    void onCause(final PermissionRequest request) {
        giveMsg(request);
    }

    @OnPermissionDenied(Manifest.permission.READ_PHONE_STATE)
    void onBreak() {
        showHelp();
    }

    @OnNeverAskAgain(Manifest.permission.READ_PHONE_STATE)
    void onNever() {
        showHelp();
    }


    private void giveMsg(PermissionRequest request) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("应用运行需获取电话、短信等权限。请许可授权");
        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                request.cancel();
                AppManager.getAppManager().finishActivity(LoginActivity.this);
            }
        });

        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                request.proceed();
            }
        });

        builder.setCancelable(false);
        builder.show();
    }

    private void showHelp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppManager.getAppManager().finishActivity(LoginActivity.this);
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }
}
